import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import {utils} from './utils';
import { validURL } from '@/utils/validate'
import router from '@/router'


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.baseURL = validURL(config.url)?"":config.baseURL;
    var data = config.data || {};

    data.app_str = '';
    let AppStr = utils.cacheGet('userappstr');
    const realIp = store.getters.realIp;
    // console.log(store.getters.realIp)
    if(realIp){
      data.realIp = realIp;
    }

    if(AppStr) {
      data.app_str = AppStr;
    }

    // console.log(data)
    // let appid = '';
    // let app_secret = '';
    // config.data = utils.returnData(data,appid,app_secret);
    config.data = utils.returnData(data);
    config.headers['Content-type'] = "application/json;charset=utf-8"

    // config.headers['Authorization'] = AppStr;
    // console.log(config)
    if (store.getters.appstr) {

    }
    // console.log(config)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    var res = response.data

    res.data=utils.aesDecrypt(res.data,res.sig);
    // console.log("返回数据",res);

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200 && res.code !== 201) {
      if(res.code == 101) {
        utils.cacheClear();
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      
      Message({
        message: res.msg || '网络错误',
        type: 'error',
        duration: 5 * 1000
      })
    

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 101 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('你的账户已经失效，请重新登录！', 'Confirm logout', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        return Promise.reject(new Error(res.message || 'Error_S')) //TODO:预留
      }
      return new Promise(function(resolve, reject) {
        reject(res.msg || 'Error_数据异常')
      }).catch(function(reason) {
        return res
      })

    } else {
      return res
    }
  },
  error => {
    if(!error.response){
      return new Promise(function(resolve, reject) {
        reject(res.msg || "Error_数据异常" )
      }).catch(function(reason) {
        return {code:52001,msg:"上传服务器错误"};
      })
    }
    const res = error.response.data
    if (error.response.status === 0) {
      Message({
        message: res.msg || "Error_数据异常",
        type: 'error',
        duration: 5 * 1000
      })
    }
    return new Promise(function(resolve, reject) {
      reject(res.msg || "Error_数据异常" )
    }).catch(function(reason) {
      return res
    })
  }
)

export default service
